package com.back.util;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExcelUtil {

//    public static List<Map<String, Object>> importExcel(String filePath, int rowNum) throws IOException {
//        //String filePath = multipartFile.getOriginalFilename();
//        InputStream ips = new FileInputStream(filePath);
//        Workbook wb = null;
//        if (filePath.endsWith(".xlsx")){
//            wb = new XSSFWorkbook(ips);
//        }else if (filePath.endsWith(".xls")){
//            wb = new HSSFWorkbook(ips);
//        }else {
//            throw new NoSuchMethodError("没有能够处理此文件的方法");
//        }
//
//        Sheet sheet = wb.getSheetAt(0);
//
//        List<Map<String, Object>> list = new ArrayList<>();
//
//        for (int i = 0; i < sheet.getLastRowNum(); i++) {
//            Row row = sheet.getRow(i);
//            Integer key = 0;
//            Map<String, Object> map = new HashMap<>();
//            for (Cell cell : row) {
//                switch (cell.getCellType()) {
//                    case BOOLEAN:
//                        map.put(key, cell.getBooleanCellValue());
//                        break;
//                    case NUMERIC:
//                        //先看是否是日期格式
//                        String dataFormat = cell.getCellStyle().getDataFormatString();	// 单元格格式
//                        if(HSSFDateUtil.isCellDateFormatted(cell)){
//                            //读取日期格式
//                            map.put(key, cell.getDateCellValue());
//                            Date date = cell.getDateCellValue();
////                      DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm");
//                            DateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
//                            //cellValue = formater.format(date);
//                            map.put(key, formater.format(date));
//                        } else {
//                            //读取数字
//                            map.put(key, cell.getNumericCellValue());
//
//                        }
//                        break;
//                    case FORMULA:
//                        //读取公式
//                        map.put(key, cell.getCellFormula());
//                        break;
//                    case STRING:
//                        //读取String
//                        map.put(key, cell.getStringCellValue());
//                        break;
//                    case ERROR:
//                    case _NONE:
//                    case BLANK:
//                        map.put(key, null);
//                        break;
//                    default:
//                        map.put(key, null);
//                }
//                key++;
//            }
//            list.add(map);
//        }
//        System.out.println("list==" + list);
//        return list;
//    }

    //private static Logger logger = Logger.getLogger(ExcelReader.class.getName()); // 日志打印类

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";

    /**
     * 根据文件后缀名类型获取对应的工作簿对象
     * @param inputStream 读取文件的输入流
     * @param fileType 文件后缀名类型（xls或xlsx）
     * @return 包含文件数据的工作簿对象
     * @throws IOException
     */
    public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
        Workbook workbook = null;
        if (fileType.equalsIgnoreCase(XLS)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileType.equalsIgnoreCase(XLSX)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }

    /**
     * 读取Excel文件内容
     * @param fileName 要读取的Excel文件所在路径
     * @return 读取结果列表，读取失败时返回null
     */
    public static List<Map<String, Object>> readExcel(String fileName) {

        Workbook workbook = null;
        FileInputStream inputStream = null;

        try {
            // 获取Excel后缀名
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 获取Excel文件
            File excelFile = new File(fileName);
            if (!excelFile.exists()) {
                //logger.warning("指定的Excel文件不存在！");
                return null;
            }

            // 获取Excel工作簿
            inputStream = new FileInputStream(excelFile);
            workbook = getWorkbook(inputStream, fileType);

            // 读取excel中的数据
            List<Map<String, Object>> resultDataList = parseExcel(workbook);

            return resultDataList;
        } catch (Exception e) {
            //logger.warning("解析Excel失败，文件名：" + fileName + " 错误信息：" + e.getMessage());
            return null;
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                //logger.warning("关闭数据流出错！错误信息：" + e.getMessage());
                return null;
            }
        }
    }



    /**
     * 解析Excel数据
     * @param workbook Excel工作簿对象
     * @return 解析结果
     */
    private static List<Map<String, Object>> parseExcel(Workbook workbook) {
        List<Map<String, Object>> resultDataList = new ArrayList<>();
        // 解析sheet
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);

            // 校验sheet是否合法
            if (sheet == null) {
                continue;
            }

            // 获取第一行数据
            int firstRowNum = sheet.getFirstRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            if (null == firstRow) {
                //logger.warning("解析Excel失败，在第一行没有读取到任何数据！");
            }

            // 解析每一行的数据，构造数据对象
            int rowStart = firstRowNum + 1;
            int rowEnd = sheet.getPhysicalNumberOfRows();

            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);

                if (null == row) {
                    continue;
                }

                Map<String, Object> resultData = convertRowToData(row);
                if (null == resultData) {
                    //logger.warning("第 " + row.getRowNum() + "行数据不合法，已忽略！");
                    continue;
                }
                resultDataList.add(resultData);
            }
        }

        return resultDataList;
    }

    /**
     * 将单元格内容转换为字符串
     * @param cell
     * @return
     */
    private static String convertCellValueToString(Cell cell) {
        if(cell==null){
            return null;
        }
        String returnValue = null;
        switch (cell.getCellType()) {
            case NUMERIC:   //数字
                Double doubleValue = cell.getNumericCellValue();

                // 格式化科学计数法，取一位整数
                DecimalFormat df = new DecimalFormat("0");
                returnValue = df.format(doubleValue);
                break;
            case STRING:    //字符串
                returnValue = cell.getStringCellValue();
                break;
            case BOOLEAN:   //布尔
                Boolean booleanValue = cell.getBooleanCellValue();
                returnValue = booleanValue.toString();
                break;
            case BLANK:     // 空值
                break;
            case FORMULA:   // 公式
                returnValue = cell.getCellFormula();
                break;
            case ERROR:     // 故障
                break;
            default:
                break;
        }
        return returnValue;
    }

    /**
     * 提取每一行中需要的数据，构造成为一个结果数据对象
     *
     * 当该行中有单元格的数据为空或不合法时，忽略该行的数据
     *
     * @param row 行数据
     * @return 解析后的行数据对象，行数据错误时返回null
     */
    private static Map<String, Object> convertRowToData(Row row) {
        Map<String, Object> resultData = new HashMap<String, Object>();

        Cell cell;
        int cellNum = 0;

        cell = row.getCell(cellNum++);
        resultData.put("var" + cellNum, convertCellValueToString(cell));
        cell = row.getCell(cellNum++);
        resultData.put("var" + cellNum, convertCellValueToString(cell));
        cell = row.getCell(cellNum++);
        resultData.put("var" + cellNum, convertCellValueToString(cell));
        cell = row.getCell(cellNum++);
        resultData.put("var" + cellNum, convertCellValueToString(cell));

        return resultData;
    }




    public static void main(String[] args) {
        //a2081ac6e434470ab2bb97e3c48ea92a.xls
        String filePath = "D:\\1临时放置文件（用完及删除）\\111\\exce\\导入观展人员模板.xlsx";
        //String filePath = "C:\\uploadFiles\\kmjnpaxy\\upexcel\\classify\\20200623\\a2081ac6e434470ab2bb97e3c48ea92a.xls";
        System.out.println(readExcel(filePath));


    }

    /**
     * 导出Excel
     * lml 2020-09-01 05:47
     * */


}
